package com.yc.thread.synch;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 */
public class SyncVSCAS {

    // 加锁对象
    private static Object o = new Object();

    private static Lock lock = new ReentrantLock();

    // 计数数量
    private static long count = 0L;

    // 线程数量大小
    private static Thread[] threads = new Thread[10000];

    // 计数循环次数
    private static final long COUNT_NUM = 100_0000;

    public static void main(String[] args) {
        SyncVSCAS s = new SyncVSCAS();
        s.testOne();

    }

    private void testOne() {
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
               synchronized (o) {
                   for (int j = 0; j < COUNT_NUM; j++) {
                       count = count + 1;
                   }
               }
            });
        }
        long start1 = System.nanoTime();
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long end1 = System.nanoTime();
//        System.out.println("synchronized耗时（纳秒）：" + (end1 - start1));
        System.out.println("synchronized耗时（秒）：" + (end1 - start1) / 1000 / 1000 / 1000);

        // ==========================================

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                try {
                    lock.lock();
                    for (int j = 0; j < COUNT_NUM; j++) {
                        count = count + 1;
                    }
                } finally {
                    lock.unlock();
                }


            });
        }
        long start2 = System.nanoTime();
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long end2 = System.nanoTime();
        System.out.println("ReentrantLock耗时（秒）：" + (end2 - start2) / 1000 / 1000 / 1000);
    }



}
